<template>
  <view class="container" :style="appThemeStyle">
    <mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ native: true }" @down="downCallback" :up="upOption"
      @up="upCallback">
      <!-- tab栏 -->
      <u-tabs class="tabsClass" :list="tabs" :is-scroll="true" v-model="curTab" :active-color="appTheme.mainBg" :duration="0.2" @change="onChangeTab" />
      <!-- 订单列表 -->
      <view class="order-list">
        <view class="order-item" v-for="(item, index) in list.data" :key="index">
          <view class="item-top">
            <view class="item-top-left">
              <text class="order-time">订单编号：{{ item.order_no }}</text>
            </view>
            <view class="item-top-right">
              <text v-if="item.state_text === '待支付'" class="state-text red">待付款</text>
              <text v-else-if="item.state_text === '已同意退货，请及时发货'" class="state-text red">待退货</text>
              <text v-else-if="item.state_text === '已发货，待平台确认'" class="state-text red">已退货待确认</text>
              <text v-else-if="item.state_text === '已同意退货并已退款'" class="state-text hui">已退款</text>
			  <text v-else class="state-text green">{{ item.state_text }}</text>
              <!-- <text v-else-if="item.state_text === '已取消'" class="state-text hui">交易关闭</text> -->
             <!-- <text v-else-if="item.state_text === '已取消' && item.refund.length === 0" class="state-text hui">{{ item.state_text }}</text>
              <text v-else-if="item.refund.length !== 0 && item.refund[0].state_text == '已同意退货，请及时发货'" class="state-text green">待退货</text>
              <text v-else-if="item.refund.length !== 0 && item.refund[0].state_text == '等待审核中'" class="state-text green">退货审核中</text>
              <text v-else-if="item.refund.length !== 0 && item.refund[0].state_text == '已发货，待平台确认'" class="state-text green">已退货待确认</text>
              <text v-else-if="item.refund.length !== 0 && item.refund[0].state_text == '已同意退货并已退款'" class="state-text hui">已退款</text>
			  <text v-else-if="item.refund.length !== 0" class="state-text green">{{ item.refund[0].state_text}}</text> -->
              
            </view>
			<!-- <view v-if="item.refund.length === 0">
				<view>测试退款</view>
			</view> -->
          </view>
		  <!-- 退款信息 -->
          <!-- 商品列表 -->
          <view class="goods-list" @click="handleTargetDetail(item.order_id)">
            <view class="goods-item" v-for="(goods, idx) in item.goods" :key="idx">
              <!-- 商品图片 -->
              <view class="goods-image">
                <image class="image" :src="goods.goods_image" mode="scaleToFill"></image>
              </view>
              <!-- 商品信息 -->
              <view class="goods-content">
                <view class="goods-title"><text class="good-name">{{ goods.goods_name }}</text></view>
                <view class="goods-props clearfix">
                  <view class="goods-props-item" v-for="(props, idx) in goods.goods_props" :key="idx">
                    <text>{{ props.value.name }}</text>
                  </view>
                </view>
				<!-- 交易信息 -->
				<!-- <view class="goods-trade">
				  <view class="goods-price">
				    <text class="unit">￥</text>
				    <text class="value">{{ goods.is_user_grade ? goods.grade_goods_price : goods.goods_price }}</text>
				  </view>
				  <view class="goods-num">
				    <text>×{{ goods.total_num }}</text>
				  </view>
				</view> -->
              </view>
              <!-- 交易信息 -->
              <view class="goods-trade">
                <view class="goods-price">
                  <text class="unit">￥</text>
                  <text class="value">{{ goods.is_user_grade ? goods.grade_goods_price : goods.goods_price }}</text>
                </view>
                <view class="goods-num">
                  <text>×{{ goods.total_num }}</text>
                </view>
				
				 <view v-if="item.refund">
					 <view v-if="item.refund.length>0">
						<view v-for="(refund, idx) in item.refund" :key="idx">
							<text v-if="refund.order_goods_id == goods.order_goods_id" class="stata-text">退款中</text>
						</view>			 
					 </view>
				  </view>
				  <view v-if="item.order_refund_id">
					   <text v-if="item.state_text =='等待审核中' || item.state_text =='已同意退货，请及时发货' || item.state_text =='已发货，待平台确认'" class="stata-text">退款中</text>
				  </view>
              </view>
            </view>
          </view>
          <!-- 订单合计 -->
         <view v-if="item.state_text === '待支付'" class="order-total">
            <text class="unit">需付款</text>
            <text class="money">￥{{ item.pay_price }}</text>
          </view>
		  <view v-else class="order-total">
		     <text class="unit">实付款</text>
		     <text v-if="item.pay_price" class="money">￥{{ item.pay_price }}</text>
		     <text v-else class="money">￥{{ item.total_pay_price }}</text>
		   </view>
          <!-- 订单操作 -->
          <view v-if="item.order_status != OrderStatusEnum.CANCELLED.value" class="order-handle">
            <view class="btn-group clearfix">
             
              <!-- 已支付进行中的订单 -->
              <!-- <block v-if="item.order_status != OrderStatusEnum.APPLY_CANCEL.value">
                <block v-if="item.pay_status == PayStatusEnum.SUCCESS.value && item.delivery_status == DeliveryStatusEnum.NOT_DELIVERED.value">
                  <view class="btn-item active" @click="onCancel(item.order_id)">去退货</view>
                </block>
              </block> -->
			  <!-- 待发货状态不需要展示按钮 -->
			  <!-- <block v-if="item.order_status != OrderStatusEnum.APPLY_CANCEL.value">
			    <block v-if="item.pay_status == PayStatusEnum.SUCCESS.value && item.delivery_status == DeliveryStatusEnum.NOT_DELIVERED.value">
			      <view class="btn-item active" @click="onCancel(item.order_id)">去退货</view>
			    </block>
			  </block> -->
              <!-- 已申请取消 -->
              <!-- <view v-else class="f-28 col-8">取消申请中</view> -->
              <!-- 未支付的订单 -->
              <block v-if="item.pay_status == PayStatusEnum.PENDING.value">
                <view class="btn-item active" @click="onPay(item.order_id)">立即支付</view>
              </block>
			  <!-- 未支付取消订单 -->
			  <block v-if="item.pay_status == PayStatusEnum.PENDING.value">
			    <view class="btn-item" @click="onCancel(item.order_id)">取消</view>
			  </block>
			  <!-- 待收货情况有退款记录的 -->
			  <view v-for="(refund, idx) in item.refund" :key="idx">
				  <block v-if="item.delivery_status == DeliveryStatusEnum.DELIVERED.value && item.receipt_status == ReceiptStatusEnum.NOT_RECEIVED.value && refund.state_text=== '已取消'">
				    <view class="btn-item active" @click="onReceipt(item.order_id)">确认收货</view>
				  </block>
				  <block v-if="item.delivery_status == DeliveryStatusEnum.DELIVERED.value && item.receipt_status == ReceiptStatusEnum.NOT_RECEIVED.value && refund.state_text === '已取消'">
				    <view class="btn-item" @click="handleTargetExpress(item.order_id)">查看物流</view>
				  </block>
			  </view>
              <!-- 确认收货 -->
			  <block v-if="item.delivery_status == DeliveryStatusEnum.DELIVERED.value && item.receipt_status == ReceiptStatusEnum.NOT_RECEIVED.value">
			    <view class="btn-item active" @click="onReceipt(item.order_id)">确认收货</view>
			  </block>
			  <block v-if="item.delivery_status == DeliveryStatusEnum.DELIVERED.value && item.receipt_status == ReceiptStatusEnum.NOT_RECEIVED.value">
			    <view class="btn-item" @click="handleTargetExpress(item.order_id)">查看物流</view>
			  </block>
			  <!-- 确认收货前申请售后退款 -->
			  <!-- <block v-if="item.delivery_status == DeliveryStatusEnum.DELIVERED.value && item.receipt_status == ReceiptStatusEnum.NOT_RECEIVED.value && item.refund.length !== 0">
			    <view class="btn-item active" @click="onReceipt(item.order_id)"></view>
			  </block> -->
              <!-- 订单评价 -->
              <block v-if="item.order_status == OrderStatusEnum.COMPLETED.value && item.is_comment == 0 && item.refund.length === 0">
                <view class="btn-item" @click="handleTargetComment(item.order_id)">评价</view>
              </block>
            </view>
          </view>
        </view>
      </view>
    </mescroll-body>
	<!-- 登录弹窗 -->
	<Loginview></Loginview>
  </view>
</template>

<script>
  import {
    DeliveryStatusEnum,
    DeliveryTypeEnum,
    OrderStatusEnum,
    PayStatusEnum,
    ReceiptStatusEnum
  } from '@/common/enum/order'
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
  import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
  import * as OrderApi from '@/api/order'
  import Loginview from '@/components/loginview/loginview' 

  // 每页记录数量
  const pageSize = 15

  // tab栏数据
  const tabs = [{
    name: `全部`,
    value: 'all'
  }, {
    name: `待支付`,
    value: 'payment'
  }, {
    name: `待发货`,
    value: 'delivery'
  }, {
    name: `待收货`,
    value: 'received'
  }, {
    name: `待评价`,
    value: 'comment'
  }, {
    name: `退款/售后`,
    value: 'refund'
  }]

  export default {
	  components:{
		  Loginview
	  },
    mixins: [MescrollMixin],
    data() {
      return {
        // 枚举类
        DeliveryStatusEnum,
        DeliveryTypeEnum,
        OrderStatusEnum,
        PayStatusEnum,
        ReceiptStatusEnum,

        // 当前页面参数
        options: { dataType: 'all' },
        // tab栏数据
        tabs,
        // 当前标签索引
        curTab: 0,
        // 订单列表数据
        list: getEmptyPaginateObj(),

        // 上拉加载配置
        upOption: {
          // 首次自动执行
          auto: true,
          // 每页数据的数量; 默认10
          page: { size: pageSize },
          // 数量要大于4条才显示无更多数据
          noMoreSize: 4,
          // 空布局
          empty: {
            tip: '亲，暂无订单记录'
          }
        },
        // 控制onShow事件是否刷新订单列表
        canReset: false
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      // 初始化当前选中的标签
      this.initCurTab(options)
      // 注册全局事件订阅: 是否刷新订单列表
      uni.$on('syncRefresh', canReset => {
        this.canReset = canReset
      })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      this.canReset && this.onRefreshList()
      this.canReset = false
    },

    /**
     * 生命周期函数--监听页面的卸载
     */
    onUnload() {
      // 卸载全局事件订阅
      uni.$off('syncRefresh')
    },

    methods: {

      // 初始化当前选中的标签
      initCurTab(options) {
		console.log(options)
        const app = this
        if (options.dataType) {
          const index = app.tabs.findIndex(item => item.value == options.dataType)
          app.curTab = index > -1 ? index : 0
        }
      },
	// 跳转到物流跟踪页面
		handleTargetExpress(orderId) {
			this.$navTo('pages/order/express/index', { orderId})
		},
      /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
		console.log('page',page)
        const app = this
        // 设置列表数据
        app.getOrderList(page.num)
          .then(list => {
            const curPageLen = list.data.length
            const totalSize = list.data.total
            app.mescroll.endBySize(curPageLen, totalSize)
          })
          .catch(() => app.mescroll.endErr())
      },

    //   // 获取订单列表
    //   getOrderList(pageNo = 1) {
    //     const app = this
    //     return new Promise((resolve, reject) => {
    //       OrderApi.list({ dataType: app.getTabValue(), page: pageNo }, { load: false })
    //         .then(result => {
				// console.log('result',result)
    //           // 合并新数据
    //           const newList = app.initList(result.data.list)
    //           app.list.data = getMoreListData(newList, app.list, pageNo)
    //           resolve(newList)
    //         })
    //     })
    //   },

    //   // 初始化订单列表数据
    //   initList(newList) {
    //     newList.data.forEach(item => {
    //       item.total_num = 0
		  // console.log('typeof',item.goods.length)
		  // if(item.goods.length != undefined){
			 //  item.goods.forEach(goods => {
			 //    item.total_num += goods.total_num
			 //  })
		  // }else{
			 //  item.total_num += item.goods.total_num
		  // }
		  
          
    //     })
    //     return newList
    //   },
 // 获取订单列表
      getOrderList(pageNo = 1) {
              const app = this
              return new Promise((resolve, reject) => {
                OrderApi.list({ dataType: app.getTabValue(), page: pageNo }, { load: false })
                  .then(result => {
      				console.log('result',result)
      				//@zf 2024-8-21 退款返回的doods 数据格式不统一，进行调整
      				if(app.getTabValue() == 'refund'){
      					result.data.list.data.forEach(item => {
      						const itme_doods = item.goods;
      						item.goods = [itme_doods];
      					})
      				}
                    // 合并新数据
                    const newList = app.initList(result.data.list)
                    app.list.data = getMoreListData(newList, app.list, pageNo)
                    resolve(newList)
                  })
              })
            },

      // 初始化订单列表数据
       initList(newList) {
              newList.data.forEach(item => {
      			item.total_num = 0
      			item.goods.forEach(goods => {
      				item.total_num += goods.total_num
      			})
              })
              return newList
            },
      // 获取当前标签项的值
      getTabValue() {
        return this.tabs[this.curTab].value
      },

      // 切换标签项
      onChangeTab(index) {
		console.log('inde',index)
        const app = this
        // 设置当前选中的标签
        app.curTab = index
        // 刷新订单列表
        app.onRefreshList()
      },

      // 刷新订单列表
      onRefreshList() {
        this.list = getEmptyPaginateObj()
        setTimeout(() => {
          this.mescroll.resetUpScroll()
        }, 120)
      },

      // 取消订单
      onCancel(orderId) {
        const app = this
        uni.showModal({
          title: '友情提示',
          content: '确认要取消该订单吗？',
          success(o) {
            if (o.confirm) {
              OrderApi.cancel(orderId)
                .then(result => {
                  // 显示成功信息
                  app.$toast(result.message)
                  // 刷新订单列表
                  app.onRefreshList()
                })
            }
          }
        });
      },

      // 确认收货
      onReceipt(orderId) {
        const app = this
        uni.showModal({
          title: '友情提示',
          content: '确认收到商品了吗？',
          success(o) {
            if (o.confirm) {
              OrderApi.receipt(orderId)
                .then(result => {
                  // 显示成功信息
                  app.$success(result.message)
                  // 刷新订单列表
                  app.onRefreshList()
                })
            }
          }
        });
      },

      // 点击去支付
      onPay(orderId) {
        this.$navTo('pages/checkout/cashier/index', { orderId })
      },

      // 跳转到订单详情页
      handleTargetDetail(orderId) {
        this.$navTo('pages/order/detail', { orderId })
      },

      // 跳转到订单评价页
      handleTargetComment(orderId) {
        this.$navTo('pages/order/comment/index', { orderId })
      }

    },

  }
</script>

<style lang="scss" scoped>
  // 项目内容
  .order-item {
    margin: 20rpx auto 20rpx auto;
    padding: 30rpx 30rpx;
    width: 94%;
	background: #FFFFFF;
	border-radius: 10rpx 10rpx 10rpx 10rpx;
	border: 2rpx solid #EDF4DA;
  }

  // 项目顶部
  .item-top {
    display: flex;
    justify-content: space-between;
    font-size: 26rpx;
    margin-bottom: 24rpx;

    .order-time {
      font-size: 28rpx;
	  color: #7D8C85;
    }

    .state-text {
      font-size: 28rpx;
    }
	.red{
		color: #ED6F4C;
	}
	.hui{
		color: #A9B5AE;
	}
	.green{
		color: #1B8147;
	}
  }

  // 商品列表
  .goods-list {
	    padding: 28rpx 0 0 0;
	    border-top: 1rpx solid #EDF4D9;
	    // border-bottom: 1rpx solid #EDF4D9;
    // 商品项
    .goods-item {
      display: flex;
      margin-bottom: 28rpx;
	 align-items: flex-start;

      // 商品图片
      .goods-image {
        width: 186rpx;
        height: 174rpx;
		border-radius: 10rpx;

        .image {
          display: block;
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }
      }

      // 商品内容
      .goods-content {
        flex: 1;
        padding-left: 16rpx;
        padding-top: 16rpx;
		.good-name{
			font-weight: bold;
			font-size: 28rpx;
			color: #042111;
		}
        .goods-title {
          font-size: 26rpx;
          max-height: 76rpx;
        }

      .goods-props {
        margin-top: 14rpx;
        color: #ababab;
        font-size: 24rpx;
        overflow: hidden;

        .goods-props-item {
          padding: 4rpx 16rpx;
          border-radius: 12rpx;
          background-color: #fcfcfc;
        }
      }


      }

      // 交易信息
      .goods-trade {
            padding-top: 16rpx;
            text-align: right;
            color: #999;
            font-size: 26rpx;

        .goods-price {
          vertical-align: bottom;
		  font-weight: bold;
		  font-size: 32rpx;
		  color: #042111;

          .unit {
            font-weight: bold;
            font-size: 32rpx;
            color: #042111;
          }
        }
		.goods-num{
		  font-weight: bold;
		  font-size: 28rpx;
		  color: #7D8D84;
		}
		.stata-text{
		  color: #dea520;
		  font-size: 26rpx;
		  margin-top: 40rpx;
		  display: block;
		}
      }

    }

  }

  // 订单合计
  .order-total {
    font-size: 26rpx;
    vertical-align: bottom;
    text-align: right;
    height: 40rpx;
    margin-bottom: 30rpx;

    .unit {
      margin-right: 10rpx;
	  font-size: 24rpx;
	  color: #042111;
    }

    .money {
      font-weight: bold;
      font-size: 32rpx;
      color: #042111;
    }
  }

  // 订单操作
  .order-handle {
	  margin-top:28rpx;
    .btn-group {
      .btn-item {
        border-radius: 10rpx;
        margin-left: 16rpx;
        font-size: 28rpx;
        float: right;
        color: #7D8D84;
        border: 2rpx solid #7D8D84;
		min-width: 146rpx;
		height: 60rpx;
		line-height: 59rpx;
		text-align: center;
        &:last-child {
          margin-left: 0;
        }

        &.active {
		  background: #ffffff;
		  color:#1B8147;
		  border: 2rpx solid #1B8147;
		  font-size: 28rpx;
		  border-radius: 10rpx 10rpx 10rpx 10rpx;
        }
      }

    }
	.btn-group{
		padding-top: 28rpx;
		border-top: 1rpx solid #EDF4D9
	}
  }

</style>
